package com.servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.google.gson.Gson;
import com.util.UploadResult;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Part part = req.getPart("myfile");
		
		String basepath = req.getServletContext().getRealPath("upload");
		String filename = UUID.randomUUID()+".jpg";
		part.write(basepath+"/"+filename);  //d://workspance/xx/upload/xxx.jpg
		
		UploadResult result = new UploadResult();
		result.setErrno(0);
		result.setData(new String[] {"upload/"+filename});
		Gson gson = new Gson();
		resp.getWriter().print(gson.toJson(result));
	}
}
